<template>
  <div class="file-list" ref="sortFileList" v-if="imageList.length > 0">
    <div class="image" v-for="(image,index) in imageList" :key="image" :style="{height: height+'px',width:width+'px'}"
         @mouseover="setImageToolIndex(index)" @mouseout="setImageToolIndex(-1)">
      <div class="image-tool" v-show="imageToolIndex==index">
        <caret-left-outlined @click="ArrUp(imageList,index)"/>
        <delete-outlined @click="deleteFile(index)"/>
        <caret-right-outlined @click="ArrDown(imageList,index)"/>
      </div>
      <a-image fit="contain" :src="image" :width="width-2" :height="height-2" style="border-radius: 5%;cursor: pointer;object-fit: contain;"></a-image>
    </div>
  </div>
</template>
<script>
export default {
  name:'ExImagePreview'
}
</script>
<script setup>
import { useVModel } from '@vueuse/core'
import Sortable from 'sortablejs'
import {ArrUp, ArrDown} from "@/utils/index"
import {ref, onUnmounted, nextTick} from "vue";

const props = defineProps({
  value: Array,
  width: {
    type: Number,
    default: 80
  },
  height: {
    type: Number,
    default: 80
  },
})
const emit = defineEmits(['update:value'])
const imageList = useVModel(props, 'value', emit)
const sortFileList = ref()
const imageToolIndex = ref(-1)
let sortable
nextTick(() => {
  sortable = Sortable.create(sortFileList.value, {
    handle: '.image',
    onEnd: evt => {
      const index = imageList.value.splice(evt.oldIndex, 1)[0]
      imageList.value.splice(evt.newIndex, 0, index)
    }
  })
})

onUnmounted((e) => {
  if (sortable) {
    sortable.destroy()
  }
})

function setImageToolIndex(index) {
  imageToolIndex.value = index
}

function deleteFile(key) {
  imageList.value.splice(key, 1)
}
</script>

<style scoped lang="scss">
.image {
  margin-right: 10px;
  position: relative;
  border: 1px dashed #dcdfe6;
  object-fit: contain;
}

.image-tool {
  position: absolute;
  width: 100%;
  height: 35px;
  cursor: pointer;
  left: 0;
  top: 0;
  z-index: 1;
  text-align: center;
  color: #fff;
  font-size: 20px;
  background-color: rgba(0, 0, 0, .5);
  border-radius: 5%;
  transition: opacity .3s;
}
.dark-theme{
  .image{
    border: 1px dashed #434343;
  }
  .image-tool {
    color: hsla(0,0%,100%,.85)
  }
}
</style>
